<template>
  <div class="page-main" v-title :data-title="dataTitle ? dataTitle : '编辑基建现场管理单'">
    <FixedMenu />
    <home-nav :userData="userinfo"></home-nav>
    <div class="container" ref="imageWrapper">
      <a-alert
        :message="alertMsg"
        :description="alertDesc"
        type="success"
        show-icon
        v-if="alertShow"
        @close="alertShow = true"
        close-text="X"
      >
      </a-alert>
      <div class="head-content">
        <span class="bold-font">编辑基建现场管理单</span>
        <div class="btn-line">
          <a-button type="link" @click="toGuied()">操作指引</a-button>
          <a-button
            v-if="infrastructure.status != '1' && infrastructure.status != '2'"
            class="hte-btn add-btn"
            type="primary"
            @click="handleSave('handleSave')"
            >保存</a-button
          >
          <a-button
            v-if="infrastructure.status != '1' && infrastructure.status != '2'"
            class="hte-btn add-btn"
            type="primary"
            @click="handleSubmit('handleSubmit')"
            >提交审批</a-button
          >
          <a-button class="hte-btn add-btn" type="primary" @click="print">打印</a-button>
        </div>
      </div>
      <div class="content">
        <a-form-model
          ref="ruleForm"
          :model="infrastructure"
          :rules="rules"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <section>
            <div class="section-header">基础信息</div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="申请流水号:" prop="applyNo">
                  <a-input v-model="infrastructure.applyNo" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人/部门:" prop="applyUser">
                  <a-input v-model="infrastructure.applyUser" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" prop="applyTime">
                  <a-date-picker
                    style="width: 100%"
                    valueFormat="YYYY-MM-DD"
                    v-model="infrastructure.applyTime"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <div style="display: flex">
                  <div style="width: 50%">
                    <a-form-model-item label="所属合同编号:" prop="hasContract">
                      <a-select
                        v-model="infrastructure.hasContract"
                        allowClear
                        :disabled="
                          infrastructure.status == '2' ||
                          (infrastructure.status == '1' && process.taskDefKey != 'apply')
                        "
                        @change="changeHasContract"
                      >
                        <a-select-option
                          v-for="(code, index) in codes['基建单据是否有合同']"
                          :key="index"
                          :value="code.code"
                        >
                          {{ code.name }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </div>
                  <div style="width: 50%" class="multipleForm">
                    <a-form-model-item
                      :labelCol="{ style: 'width: 0px' }"
                      :prop="infrastructure.hasContract == '1' ? 'contractNumber' : ''"
                    >
                      <a-input-search
                        v-model="infrastructure.contractNumber"
                        @search="openProjectSelector"
                        :readOnly="infrastructure.hasContract == '1'"
                        :disabled="
                          infrastructure.status == '2' ||
                          (infrastructure.status == '1' && process.taskDefKey != 'apply')
                        "
                        @change="changeContractNumber"
                      />
                    </a-form-model-item>
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同名称:" prop="contractName">
                  <a-input
                    v-model="infrastructure.contractName"
                    :disabled="
                      infrastructure.hasContract == '1' ||
                      infrastructure.status == '2' ||
                      (infrastructure.status == '1' && process.taskDefKey != 'apply')
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="费用号支出号:" prop="costNumber">
                  <a-input
                    v-model="infrastructure.costNumber"
                    placeholder="请输入费用号"
                    :disabled="
                      infrastructure.hasContract == '1' ||
                      infrastructure.status == '2' ||
                      (infrastructure.status == '1' && process.taskDefKey != 'apply')
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8"> </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="签订公司/代码:" prop="companyCode">
                  <a-select
                    :value="
                      infrastructure.companyName ? infrastructure.companyName + '/' + infrastructure.companyCode : ''
                    "
                    :disabled="
                      infrastructure.hasContract == '1' ||
                      infrastructure.status == '2' ||
                      (infrastructure.status == '1' && process.taskDefKey != 'apply')
                    "
                    @change="(v) => changeSignCompanyCode(v)"
                  >
                    <a-select-option
                      v-for="(item, index) in signCompany"
                      :key="'companyName' + index"
                      :value="item.componyNo"
                    >
                      {{ item.componyName + '/' + item.componyNo }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="供应商/编码:" prop="supplierCode">
                  <a-input-search
                    :value="
                      infrastructure.supplierName ? infrastructure.supplierName + '/' + infrastructure.supplierCode : ''
                    "
                    :disabled="
                      infrastructure.hasContract == '1' ||
                      infrastructure.status == '2' ||
                      (infrastructure.status == '1' && process.taskDefKey != 'apply')
                    "
                    readOnly
                    @search="showSupplierSelector = true"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="采购订单号:" prop="poNo">
                  <a-input
                    v-model="infrastructure.poNo"
                    :disabled="
                      infrastructure.hasContract == '1' ||
                      infrastructure.status == '2' ||
                      (infrastructure.status == '1' && process.taskDefKey != 'apply')
                    "
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="公文类型" prop="docType">
                  <a-select
                    v-model="infrastructure.docType"
                    :default-active-first-option="false"
                    :show-arrow="false"
                    :filter-option="false"
                    :not-found-content="null"
                    allowClear
                    @change="getNextNum(1)"
                    :disabled="
                      infrastructure.status == '2' || (infrastructure.status == '1' && process.taskDefKey != 'apply')
                    "
                  >
                    <a-select-option v-for="item in codes.InfrastructureDocType" :key="item.code" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据类型" prop="type">
                  <a-select
                    v-model="infrastructure.type"
                    :default-active-first-option="false"
                    :show-arrow="false"
                    :filter-option="false"
                    :not-found-content="null"
                    allowClear
                    @change="getNextNum(0)"
                    :disabled="
                      infrastructure.status == '2' || (infrastructure.status == '1' && process.taskDefKey != 'apply')
                    "
                  >
                    <a-select-option v-for="item in codes.InfrastructureType" :key="item.code" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" prop="num">
                  <a-input
                    v-model="infrastructure.num"
                    placeholder="自动生成，可修改"
                    :disabled="infrastructure.status == '2'"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="16">
                <a-form-model-item label="单据名称" prop="name">
                  <a-input
                    v-model="infrastructure.name"
                    :disabled="
                      infrastructure.status == '2' || (infrastructure.status == '1' && process.taskDefKey != 'apply')
                    "
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="申报金额(元)" prop="amount">
                  <a-input
                    v-model="infrastructure.amount"
                    placeholder="由造价专员填写，不扣罚则填0"
                    :disabled="infrastructure.status == '2'"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <div style="display: flex">
                  <div style="width: 70%">
                    <a-form-model-item label="审批金额(元):">
                      <a-input
                        v-model="infrastructure.auditAmount"
                        placeholder="由造价专员填写，不扣罚则填0"
                        :disabled="
                          infrastructure.status == '2' || ['budget', 'budget1'].indexOf(process.taskDefKey) < 0
                        "
                      />
                    </a-form-model-item>
                  </div>
                  <div style="width: 30%" class="multipleForm">
                    <a-form-model-item :labelCol="{ style: 'width: 0px' }">
                      <a-select
                        v-model="infrastructure.priceQuotation"
                        allowClear
                        :disabled="
                          infrastructure.status == '2' || ['budget', 'budget1'].indexOf(process.taskDefKey) < 0
                        "
                        default="1"
                      >
                        <a-select-option
                          v-for="(code, index) in codes['基建单据报价方式']"
                          :key="index"
                          :value="code.code"
                        >
                          {{ code.name }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </div>
                </div>
              </a-col>
              <a-col :span="8">
                <a-button size="small" @click="openChangeRecordSelector">选择变更单</a-button>
              </a-col>
            </a-row>
            <div style="display: flex; flex-direction: column; justify-content: center; padding: 10px">
              <a-table
                style="width: 90%"
                :columns="changeRecordColumns"
                :data-source="filterChangeRecords"
                rowKey="id"
                bordered
                :pagination="false"
              >
              </a-table>
            </div>
          </section>

          <section>
            <div class="section-header" style="justify-content: flex-start">
              第一阶段<span style="font-size: 12px; color: #ccc; font-weight: normal; padding-left: 30px"
                >合同变更的通知单阶段或问题沟通的提出阶段</span
              >
            </div>
            <a-collapse v-model="showStage1" :bordered="false">
              <a-collapse-panel key="showStage1">
                <a-form-model-item label="主要内容描述:" prop="stageContent1">
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageAdvice1"
                    v-if="
                      !infrastructure.status ||
                      infrastructure.status == '0' ||
                      infrastructure.status == '3' ||
                      (infrastructure.status == '1' &&
                        flowTask.currentUserId == curUserId &&
                        ['apply', 'document0', 'document'].indexOf(process.taskDefKey) > -1)
                    "
                  />
                  <a-textarea
                    v-else
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageAdvice1"
                    disabled
                  />
                </a-form-model-item>
                <a-form-model-item label="处理要求或建议" prop="stageAdvice1">
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageContent1"
                    v-if="
                      !infrastructure.status ||
                      infrastructure.status == '0' ||
                      infrastructure.status == '3' ||
                      (infrastructure.status == '1' &&
                        flowTask.currentUserId == curUserId &&
                        ['apply', 'document0', 'document'].indexOf(process.taskDefKey) > -1)
                    "
                  />
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageContent1"
                    v-else
                    disabled
                  />
                </a-form-model-item>
                <div class="section-header" style="margin-top: 10px">
                  <div style="display: flex; justify-content: space-start">
                    附件上传<span style="font-size: 12px; color: #ccc; padding-left: 30px; font-weight: normal"
                      >可附上说明文档、图纸等资料</span
                    >
                  </div>
                  <div style="display: flex; justify-content: flex-end; item-align: center">
                    <ht-upload
                      v-if="
                        infrastructure.id &&
                        (!infrastructure.status ||
                          infrastructure.status == '0' ||
                          infrastructure.status == '3' ||
                          (infrastructure.status == '1' &&
                            flowTask.currentUserId == curUserId &&
                            ['apply', 'major', 'proManager', 'majorHeader0', 'document0'].indexOf(process.taskDefKey) >
                              -1))
                      "
                      class="upload-demo"
                      dbKey="Trd"
                      busField="Infrastructure"
                      :busType="busType"
                      :busKey="infrastructure.id + '_stage_1'"
                      ftpKey="ftp"
                      v-model="fileList1"
                      :show-file-list="false"
                      :before-upload="() => beforUpload(1)"
                      :on-success="afterUpload"
                    >
                      <a-button class="hte-btn add-btn" type="primary" icon="plus">上传</a-button>
                    </ht-upload>
                    <a-button @click="handleDownload(1)" style="margin-left: 10px"> 打包下载 </a-button>
                    <a-button
                      @click="handleDownloadTemplate('3f01e7e664144fab8b56d6f27ebeccfb')"
                      style="margin-left: 10px"
                    >
                      模板
                    </a-button>
                  </div>
                </div>
                <a-table
                  class="hte-table-content"
                  :columns="attachColumns"
                  :data-source="attachs[1]"
                  :pagination="false"
                  rowKey="id"
                  :row-selection="{
                    selectedRowKeys: selectedAttachKeys1,
                    onChange: (keys, rows) => onSelectAttachChange(keys, rows, 1),
                  }"
                  size="middle"
                  bordered
                  :customRow="(record) => customAttachRow(record, 1)"
                >
                  <template slot="actionRender" slot-scope="text, record">
                    <span
                      v-if="
                        !infrastructure.status ||
                        infrastructure.status == '0' ||
                        (infrastructure.status == '3' && record.uploader == curUserId && ['create','apply','workReport','reject'].indexOf(record.busType)>-1) ||
                        (infrastructure.status == '1' && process.taskDefKey=='apply' &&  record.uploader == curUserId && ['create','apply','workReport','reject'].indexOf(record.busType)>-1) ||
                        (infrastructure.status == '1' &&
                          flowTask.currentUserId == curUserId &&
                          record.uploader == curUserId &&
                          (record.busType == process.taskDefKey || record.busType=='workReport') &&
                          ['apply', 'major', 'proManager', 'majorHeader0', 'document0'].indexOf(
                            process.taskDefKey
                          ) > -1)
                      "
                      class="font-active"
                      @click="handleDelAttach(record, 1)"
                    >
                      删除
                    </span>
                  </template>
                  <template slot="previewRender" slot-scope="text, record">
                    <span class="font-active" @click="handlePreview(record)">
                      {{ record.fileName }}
                    </span>
                  </template>
                  <template slot="fileSizeRender" slot-scope="text, record">
                    {{ formatFileSize(text) }}
                  </template>
                  <template slot="busTypeRender" slot-scope="text, record">
                    {{ flowNodes[text] }}
                  </template>
                </a-table>
              </a-collapse-panel>
            </a-collapse>
          </section>

          <section
            v-if="
              infrastructure.status == '2' ||
              infrastructure.status == '3' ||
              (infrastructure.status == '1' &&
                [
                  'document',
                  'major1',
                  'budget',
                  'budgetHeader',
                  'proManager1',
                  'majorHeader',
                  'document1',
                  'major2',
                  'budget1',
                  'budgetHeader1',
                  'projectManager2',
                  'majorHeader1',
                  'document2',
                ].indexOf(process.taskDefKey) > -1)
            "
          >
            <div class="section-header" style="justify-content: flex-start">
              第二阶段<span style="font-size: 12px; color: #ccc; font-weight: normal; padding-left: 30px"
                >合同变更的报价单阶段或问题沟通的回复阶段</span
              >
            </div>
            <a-collapse v-model="showStage2" :bordered="false">
              <a-collapse-panel key="showStage2">
                <a-form-model-item label="主要内容描述:" prop="stageContent2">
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageContent2"
                    v-if="
                      infrastructure.status == '1' &&
                      flowTask.currentUserId == curUserId &&
                      ['document', 'document1'].indexOf(process.taskDefKey) > -1
                    "
                  />
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageContent2"
                    v-else
                    disabled
                  />
                </a-form-model-item>
                <a-form-model-item label="处理要求或建议" prop="stageAdvice2">
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageAdvice2"
                    v-if="
                      infrastructure.status == '1' &&
                      flowTask.currentUserId == curUserId &&
                      ['document', 'document1'].indexOf(process.taskDefKey) > -1
                    "
                  />
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageAdvice2"
                    v-else
                    disabled
                  />
                </a-form-model-item>
                <div class="section-header" style="margin-top: 10px">
                  <div style="display: flex; justify-content: space-start">
                    附件上传<span style="font-size: 12px; color: #ccc; padding-left: 30px; font-weight: normal"
                      >可附上说明文档、图纸等资料</span
                    >
                  </div>
                  <div style="display: flex; justify-content: flex-end">
                    <ht-upload
                      v-if="
                        infrastructure.status == '1' &&
                        flowTask.currentUserId == curUserId &&
                        ['document', 'major1', 'budget', 'budgetHeader', 'proManager1', 'majorHeader'].indexOf(
                          process.taskDefKey
                        ) > -1
                      "
                      class="upload-demo"
                      dbKey="Trd"
                      busField="Infrastructure"
                      :busType="busType"
                      :busKey="infrastructure.id + '_stage_2'"
                      ftpKey="ftp"
                      v-model="fileList2"
                      :show-file-list="false"
                      :before-upload="() => beforUpload(2)"
                      :on-success="afterUpload"
                    >
                      <a-button class="hte-btn add-btn" type="primary" icon="plus">上传</a-button>
                    </ht-upload>
                    <a-button @click="handleDownload(2)" style="margin-tleft: 10px"> 打包下载 </a-button>
                    <a-button
                      @click="handleDownloadTemplate('3f01e7e664144fab8b56d6f27ebeccfb')"
                      style="margin-left: 10px"
                    >
                      模板
                    </a-button>
                  </div>
                </div>
                <a-table
                  class="hte-table-content"
                  :columns="attachColumns"
                  :data-source="attachs[2]"
                  :pagination="false"
                  rowKey="id"
                  :row-selection="{
                    selectedRowKeys: selectedAttachKeys2,
                    onChange: (keys, rows) => onSelectAttachChange(keys, rows, 2),
                  }"
                  size="middle"
                  bordered
                  :customRow="(record) => customAttachRow(record, 2)"
                >
                  <template slot="actionRender" slot-scope="text, record">
                    <span
                      v-if="
                        infrastructure.status == '1' &&
                        flowTask.currentUserId == curUserId &&
                        record.uploader == curUserId &&
                        (record.busType == process.taskDefKey || record.busType=='workReport') &&
                        [
                          'document',
                          'major1',
                          'budget',
                          'budgetHeader',
                          'proManager1',
                          'majorHeader',
                        ].indexOf(process.taskDefKey) > -1
                      "
                      class="font-active"
                      @click="handleDelAttach(record, 2)"
                    >
                      删除
                    </span>
                  </template>
                  <template slot="previewRender" slot-scope="text, record">
                    <span class="font-active" @click="handlePreview(record)">
                      {{ record.fileName }}
                    </span>
                  </template>
                  <template slot="fileSizeRender" slot-scope="text, record">
                    {{ formatFileSize(text) }}
                  </template>
                  <template slot="busTypeRender" slot-scope="text, record">
                    {{ flowNodes[text] }}
                  </template>
                </a-table>
              </a-collapse-panel>
            </a-collapse>
          </section>
          <section
            v-if="
              infrastructure.status == '2' ||
              infrastructure.status == '3' ||
              (infrastructure.status == '1' &&
                [
                  'document1',
                  'major2',
                  'budget1',
                  'budgetHeader1',
                  'projectManager2',
                  'majorHeader1',
                  'document2',
                ].indexOf(process.taskDefKey) > -1)
            "
          >
            <div class="section-header" style="justify-content: flex-start">
              第三阶段<span style="font-size: 12px; color: #ccc; font-weight: normal; padding-left: 30px"
                >合同变更的签证单阶段</span
              >
            </div>
            <a-collapse v-model="showStage3" :bordered="false">
              <a-collapse-panel key="showStage3">
                <a-form-model-item label="主要内容描述:" prop="stageContent3">
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageContent3"
                    v-if="
                      infrastructure.status == '1' &&
                      flowTask.currentUserId == curUserId &&
                      ['document1', 'document2'].indexOf(process.taskDefKey) > -1
                    "
                  />
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageContent3"
                    v-else
                    disabled
                  />
                </a-form-model-item>
                <a-form-model-item label="处理要求或建议" prop="stageAdvice3">
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageAdvice3"
                    v-if="
                      infrastructure.status == '1' &&
                      flowTask.currentUserId == curUserId &&
                      ['document1', 'document2'].indexOf(process.taskDefKey) > -1
                    "
                  />
                  <a-textarea
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    :maxLength="1000"
                    v-model="infrastructure.stageAdvice3"
                    v-else
                    disabled
                  />
                </a-form-model-item>
                <div class="section-header" style="margin-top: 10px">
                  <div style="display: flex; justify-content: space-start">
                    附件上传<span style="font-size: 12px; color: #ccc; padding-left: 30px; font-weight: normal"
                      >可附上说明文档、图纸等资料</span
                    >
                  </div>
                  <div style="display: flex; justify-content: flex-end">
                    <ht-upload
                      v-if="
                        infrastructure.status == '1' &&
                        flowTask.currentUserId == curUserId &&
                        [
                          'document1',
                          'major2',
                          'budget1',
                          'budgetHeader1',
                          'projectManager2',
                          'majorHeader1',
                          'majorHeader1',
                          'document2',
                        ].indexOf(process.taskDefKey) > -1
                      "
                      class="upload-demo"
                      dbKey="Trd"
                      busField="Infrastructure"
                      :busType="busType"
                      :busKey="infrastructure.id + '_stage_3'"
                      ftpKey="ftp"
                      v-model="fileList3"
                      :show-file-list="false"
                      :before-upload="() => beforUpload(3)"
                      :on-success="afterUpload"
                    >
                      <a-button class="hte-btn add-btn" type="primary" icon="plus">上传</a-button>
                    </ht-upload>
                    <a-button @click="handleDownload(3)" style="margin-left: 10px"> 打包下载 </a-button>
                    <a-button
                      @click="handleDownloadTemplate('3f01e7e664144fab8b56d6f27ebeccfb')"
                      style="margin-left: 10px"
                    >
                      模板
                    </a-button>
                  </div>
                </div>
                <a-table
                  class="hte-table-content"
                  :columns="attachColumns"
                  :data-source="attachs[3]"
                  :pagination="false"
                  rowKey="id"
                  :row-selection="{
                    selectedRowKeys: selectedAttachKeys3,
                    onChange: (keys, rows) => onSelectAttachChange(keys, rows, 3),
                  }"
                  size="middle"
                  bordered
                  :customRow="(record) => customAttachRow(record, 3)"
                >
                  <template slot="actionRender" slot-scope="text, record">
                    <span
                      v-if="
                        infrastructure.status == '1' &&
                        flowTask.currentUserId == curUserId &&
                        record.uploader == curUserId &&
                        (record.busType == process.taskDefKey || record.busType=='workReport') &&
                        [
                          'document1',
                          'major2',
                          'budget1',
                          'budgetHeader1',
                          'projectManager2',
                          'majorHeader1',
                          'majorHeader1',
                          'document2',
                        ].indexOf(process.taskDefKey) > -1
                      "
                      class="font-active"
                      @click="handleDelAttach(record, 3)"
                    >
                      删除
                    </span>
                  </template>
                  <template slot="previewRender" slot-scope="text, record">
                    <span class="font-active" @click="handlePreview(record)">
                      {{ record.fileName }}
                    </span>
                  </template>
                  <template slot="fileSizeRender" slot-scope="text, record">
                    {{ formatFileSize(text) }}
                  </template>
                  <template slot="busTypeRender" slot-scope="text, record">
                    {{ flowNodes[text] }}
                  </template>
                </a-table>
              </a-collapse-panel>
            </a-collapse>
          </section>
          <section v-if="infrastructure.flowId">
            <div class="section-header" style="display: flex; justify-content: flex-start; justify-items: center">
              <div>审批记录</div>
              <!-- <a-switch
                style="margin-left: 20px"
                v-model="showProgress"
                checked-children="展开审批流程进度"
                un-checked-children="关闭审批流程进度"
              /> -->
            </div>
            <div>
              <ht-approval
                :key="infrastructure.flowId"
                ref="childrenRef"
                :process-instance-id="infrastructure.flowId"
                :custom="custom"
                :options="options"
                @submit="afterSubmit"
                @reject="afterReject"
                @back="backAction"
                @cancelSubmit="afterCancelSubmit"
                :before-fill-opinion="saveNotifyOpinion"
                :before-submit="beforeSubmit"
                :before-reject="beforeReject"
                :before-back="beforeBack"
                :show-task-history="true"
                :history-dialog="historyDialog"
                :task-load="taskLoad"
                :message-id="messageId"
                :showPrintBtn="showPrintBtn"
                :show-upload-btn="false"
                :hidden-task-def-key="hiddenTaskDefKey"
                :print="print"
                :snapshotConfigs="snapshotConfigs"
              >
              </ht-approval>
            </div>
          </section>
        </a-form-model>
      </div>
    </div>
    <WorkReportProjectSelector @close="closeWorkReportProjectSelector" ref="WorkReportProjectSelector" />
    <ProcessUserSelect ref="ProcessUserSelect" @selectUserConfirm="selectUserConfirm" />
    <SupplierSelector :show="showSupplierSelector" @close="selectSupplier" />
    <div style="visibility: hidden; position: fixed">
      <InfrastructureDetailPrint
        ref="InfrastructureDetailPrint"
        :infrastructure="infrastructure"
        :codes="codes"
        :comments="comments"
        :attachs="attachs"
        :process="process"
      />
      <ChangeRecordSelector ref="ChangeRecordSelector" @select="closeChangeRecordSelector" />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getAction, postAction, deleteAction, previewAttach } from '@/api/manage'
import { formatDate } from '@/utils/util'
import '@/config/upload.install.js'
import { FlowMixin } from '@/mixins/FlowMixin'
import { formatFileSize, endWith } from '@/utils/common.js'
import { Modal } from 'ant-design-vue'
import { TableMixin } from '@/mixins/TableMixin'
import { CodesMixin } from '@/mixins/CodesMixin'
import Bus from '@/views/workReport/layout/tag/bus'
export default {
  mixins: [TableMixin, FlowMixin, CodesMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    htApproval: () => import('@/config/ht-approval.umd.min.js'),
    ProcessUserSelect: () => import('@/components/tools/ProcessUserSelect'),
    SupplierSelector: () => import('@/views/workReport/util/SupplierSelector'),
    InfrastructureDetailPrint: () => import('@/views/workReport/infrastructure/InfrastructureDetailPrint'),
    WorkReportProjectSelector: () => import('@/views/workReport/project/ProjectSelector'),
    ChangeRecordSelector: () => import('@/views/projectChange/ChangeRecordSelector'),
    FixedMenu: () => import('@/views/workReport/home/FixedMenu'),
  },
  data() {
    return {
      dataTitle: this.$route ? this.$route.name : '',
      snapshotConfigs: [
        {
          type: 'ref',
          value: 'imageWrapper',
        },
      ],
      curUserId: this.$store.getters.userInfo.username,
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      urls: {
        info: '/infrastructure/info',
        edit: '/infrastructure/edit',
        myPermission: '/workReport/project/myPermission',
        codes: '/manage/codeInfo/queryByTypes',
        getAttachs: '/tp/attach/getAttaches',
        getNextNum: '/infrastructure/nextNum',
        updateStatus: '/infrastructure/updateStatus',
        flowNode: '/infrastructure/flowNode',
        startFlow: '/infrastructure/startFlow',
        getProcess: '/workReport/payment/getProcess',
        deleteAttach: '/com.haday.hte.attach/attachInfo/delete',
        loadSignCompany: '/hte/contract/loadSignCompany',
        changeRecordList: '/projectChange/list',
        getProcessComment: '/workReport/payment/getProcessComment',
        downLoadBatchWithFileName: '/common/downLoadBatchWithFileName',
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      rules: {
        docType: [{ required: true, message: '请输入', trigger: 'blur' }],
        type: [{ required: true, message: '请选择', trigger: 'blur' }],
        num: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入', trigger: 'blur' }],
        auditAmount: [{ required: true, message: '请输入', trigger: 'blur' }],
        stageContent1: [{ required: true, message: '请输入', trigger: 'blur' }],
        stageAdvice1: [{ required: true, message: '请输入', trigger: 'blur' }],
        stageContent2: [{ required: true, message: '请输入', trigger: 'blur' }],
        stageAdvice2: [{ required: true, message: '请输入', trigger: 'blur' }],
        stageContent3: [{ required: true, message: '请输入', trigger: 'blur' }],
        stageAdvice3: [{ required: true, message: '请输入', trigger: 'blur' }],
        hasContract: [{ required: true, message: '请选择', trigger: 'blur' }],
        priceQuotation: [{ required: true, message: '请选择', trigger: 'blur' }],
        contractNumber: [{ required: true, message: '请选择', trigger: 'blur' }],
        contractName: [{ required: true, message: '请输入', trigger: 'blur' }],
        costNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        companyCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        supplierCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        purchaseOrderNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      id: '',
      infrastructure: { amount: 0, auditAmount: 0 },
      stageIndex: 1,
      attachs: [[], [], []],
      permission: [],
      showContractSelector: false,
      selectedAttachRows1: [],
      selectedAttachKeys1: [],
      selectedAttachRows2: [],
      selectedAttachKeys2: [],
      selectedAttachRows3: [],
      selectedAttachKeys3: [],
      fileList1: [],
      fileList2: [],
      fileList3: [],
      codes: {},
      attachColumns: [
        {
          title: '附件名称',
          dataIndex: 'fileName',
          align: 'center',
          width: '330px',
          ellipsis: true,
          scopedSlots: { customRender: 'previewRender' },
        },
        {
          title: '上传节点',
          dataIndex: 'busType',
          align: 'center',
          width: '330px',
          ellipsis: true,
          scopedSlots: { customRender: 'busTypeRender' },
        },
        {
          title: '文件大小',
          dataIndex: 'size',
          align: 'center',
          width: '130px',
          ellipsis: true,
          scopedSlots: { customRender: 'fileSizeRender' },
        },
        {
          title: '上传人',
          dataIndex: 'uploaderName',
          align: 'center',
          width: '100px',
          ellipsis: true,
        },
        {
          title: '上传时间',
          dataIndex: 'uploadTime',
          align: 'center',
          width: '130px',
          ellipsis: true,
        },
        ,
        {
          title: '操作',
          align: 'center',
          width: '130px',
          ellipsis: true,
          scopedSlots: { customRender: 'actionRender' },
        },
      ],
      process: { taskDefKey: '' },
      submitType: 'submit',
      hasConfirm: false,
      showProgress: false,
      showSupplierSelector: false,
      searchTimeOut: null,
      changeRecords: [],
      changeRecordColumns: [
        {
          title: '序号',
          dataIndex: 'sortIndex',
          width: '80px',
          align: 'center',
          customRender: (text, record, index) => {
            return index + 1
          },
        },
        {
          title: '变更单号',
          dataIndex: 'projectChangeNo',
          align: 'center',
          width: '130px',
          customCell: () => {
            return this.customCellRender(130)
          },
          customRender: (text, record) => {
            return this.tooltipActiveRender(text, record, 'toChangeRecordDetail')
          },
        },
        {
          title: '项目变更名称',
          dataIndex: 'projectChangeName',
          align: 'left',
          width: '230px',
          customCell: () => {
            return this.customCellRender(230)
          },
          customRender: (text, record) => {
            return this.tooltipRender(text, record)
          },
        },
        {
          title: '变更类型',
          dataIndex: 'changeType',
          align: 'center',
          width: '100px',
          customCell: () => {
            return this.customCellRender(100)
          },
          customRender: (text, record) => {
            return this.tooltipRender(this.getCodeNames(text, '工程项目变更类型'), record)
          },
        },
        {
          title: '申请人',
          dataIndex: 'createUserName',
          align: 'center',
          width: '80px',
        },
        {
          title: '申请日期',
          dataIndex: 'submitTime',
          align: 'center',
          width: '100px',
          customCell: () => {
            return this.customCellRender(100)
          },
          customRender: (text, record) => {
            return this.timeRender(text, record, 'yyyy-MM-dd')
          },
        },
      ],
      signCompany: [],
      comments: [],
      alertMsg: '',
      alertDesc: '',
      alertShow: false,
      currentRoute: this.$route,
      flowNodes: {
        workReport: '旧数据,无法区分',
        create: '创建',
        reject: '审批不通过',
        apply: '申请人',
        major: '1-专业负责人',
        proManager: '1-项目经理',
        majorHeader0: '1-专业主管',
        document0: '1-资料员',
        document: '2-资料员',
        major1: '2-专业负责人',
        budget: '2-造价专员',
        budgetHeader: '2-造价主管',
        proManager1: '2-项目经理',
        majorHeader: '2-专业主管',
        document1: '3-资料员',
        major2: '3-专业负责人',
        budget1: '3-造价专员',
        budgetHeader1: '申请人',
        projectManager2: '3-项目经理',
        majorHeader1: '3-专业主管',
        document2: '4-资料员',
      },
    }
  },
  computed: {
    labels() {
      let temp = []
      let isNeedMajor = 1
      // if (this.$refs.ProcessUserSelect) {
      //   let fields = this.$refs.ProcessUserSelect.columns
      //   if (fields && fields.length > 1) {
      //     isNeedMajor = fields[0][fields[0]['node'] + 'Id'] == fields[1][fields[1]['node'] + 'Id'] ? 0 : 1
      //   }
      // }
      let isNeedStage3 = this.infrastructure.type && this.infrastructure.type == '1' ? 1 : 0
      temp.push('申请人')
      if (isNeedMajor == 1) {
        temp.push('1-专业负责人')
      }
      temp.push('1-项目经理')
      temp.push('1-资料员')
      temp = [...temp, ...this.calcStageflowNode(2)]
      if (isNeedStage3 == 1) {
        temp = [...temp, ...this.calcStageflowNode(3)]
      }
      temp.push('4-资料员')
      return temp
    },
    showStage1: {
      get: function () {
        return ['apply', 'major', 'proManager', 'document0'].indexOf(this.currentTask.taskDefKey) > -1 ||
          (this.infrastructure.status != '1' && this.infrastructure.status != '2')
          ? 'showStage1'
          : 'hideStage1'
      },
      set: function (value) {},
    },
    showStage2: {
      get: function () {
        return ['document', 'document1', 'major1', 'budget', 'budgetHeader', 'proManager1', 'majorHeader'].indexOf(
          this.currentTask.taskDefKey
        ) > -1
          ? 'showStage2'
          : 'hideStage2'
      },
      set: function (value) {},
    },
    showStage3: {
      get: function () {
        return [
          'document1',
          'major2',
          'budget1',
          'budgetHeader1',
          'projectManager2',
          'majorHeader1',
          'document2',
        ].indexOf(this.currentTask.taskDefKey) > -1
          ? 'showStage3'
          : 'hideStage3'
      },
      set: function (value) {},
    },
    filterChangeRecords() {
      let tempList = []
      if (this.infrastructure.changeRecordId) {
        let changeRecordId = this.infrastructure.changeRecordId.split(',')
        if (this.changeRecords) {
          this.changeRecords.forEach((c) => {
            if (changeRecordId.indexOf(c.id + '') > -1) {
              tempList.push(c)
            }
          })
        }
      }
      return tempList
    },
    busType: {
      get: function () {
        if (this.currentTask && this.currentTask.taskDefKey) {
          return this.currentTask.taskDefKey
        } else {
          if (this.infrastructure.status == 0 || !this.infrastructure.status) {
            return 'create'
          } else {
            if (this.infrastructure.status == 3) {
              return 'reject'
            }
          }
        }
      },
      set: function (value) {},
    },
  },
  async mounted() {
    this.fetchSignCompany()
    this.init()
  },
  methods: {
    endWith,
    formatDate,
    formatFileSize,
    async init() {
      this.hasConfirm = false
      await this.fetchCodes()
      this.fetchPermission()
      if (this.id) {
        this.fetchInfrastructure(this.id)
      }
    },
    fetchInfrastructure(id) {
      this.id = id
      if (!this.id) {
        return
      }
      getAction(this.urls.info + '/' + id).then((res) => {
        if (res.success) {
          this.infrastructure = res.result
          if (!this.infrastructure.amount) {
            this.$set(this.infrastructure, 'amount', 0)
          }
          if (!this.infrastructure.auditAmount) {
            this.$set(this.infrastructure, 'auditAmount', 0)
          }
          if (this.infrastructure.flowId) {
            this.fetchProcess(this.infrastructure.flowId)
          }
          this.toChangeRecordList()
        } else {
          this.$messageWorkReport.error('获取基建现场管理单信息失败:' + res.message)
        }
      })
      this.fetchAttachs(1)
      this.fetchAttachs(2)
      this.fetchAttachs(3)
    },
    fetchProcess(flowId) {
      getAction(this.urls.getProcess + '/' + flowId, {}).then((res) => {
        if (res.success) {
          this.process = res.result
          if (!this.process) {
            this.process = { taskDefKey: '' }
          }
        } else {
          this.$messageWorkReport.error(res.message)
        }
      })
    },
    initInfrastructure(project) {
      if (project) {
        this.$set(this.infrastructure, 'contractNumber', project.contractNumber)
        this.$set(this.infrastructure, 'contractName', project.contractName)
        this.$set(this.infrastructure, 'poNo', project.busKey)
        this.$set(this.infrastructure, 'supplierName', project.supplierName)
        this.$set(this.infrastructure, 'supplierCode', project.supplierCode)
        this.$set(this.infrastructure, 'companyName', project.signCompany)
        this.$set(this.infrastructure, 'companyCode', project.signCompanyCode)
        if (project.costNumber) {
          let costNumbers = project.costNumber.split(',')
          this.$set(this.infrastructure, 'costNumber', costNumbers[0])
        }
      }
    },
    fetchCodes() {
      let types = []
      types.push('InfrastructureStatus')
      types.push('InfrastructureType')
      types.push('InfrastructureDocType')
      types.push('基建单据是否有合同')
      types.push('基建单据报价方式')
      types.push('工程项目变更类型')
      getAction(this.urls.codes, { types: types.join(',') }).then((res) => {
        if (res.success) {
          this.codes = { ...this.codes, ...res.result }
        }
      })
    },
    fetchPermission() {
      getAction(this.urls.myPermission, { projectId: '-1' }).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = false
      if (this.permission && powers) {
        for (let p of powers) {
          if (this.permission.indexOf(p) > -1) {
            hasPower = true
            break
          }
        }
      }
      return hasPower
    },
    openProjectSelector() {
      this.$refs.WorkReportProjectSelector.init()
    },
    async closeWorkReportProjectSelector(project) {
      if (project) {
        this.$set(this.infrastructure, 'contractNumber', project.contractNumber)
        this.$set(this.infrastructure, 'contractName', project.contractName)
        this.$set(this.infrastructure, 'poNo', project.busKey)
        this.$set(this.infrastructure, 'supplierName', project.supplierName)
        this.$set(this.infrastructure, 'supplierCode', project.supplierCode)
        this.$set(this.infrastructure, 'companyName', project.signCompany)
        this.$set(this.infrastructure, 'companyCode', project.signCompanyCode)
        this.$set(this.infrastructure, 'costNumber', project.costNumber)
      }
      this.changeContractNumber()
      this.getNextNum(0)
    },

    handleSave(action) {
      postAction(this.urls.edit, this.infrastructure).then((res) => {
        if (res.success) {
          this.infrastructure = res.result
          this.$messageWorkReport.success('保存成功')
          if (this.$route.path.startsWith('/infrastructure/add')) {
            let urlJump = this.$router.resolve({ path: '/infrastructure/edit/' + this.infrastructure.id })
            window.open(urlJump.href, '_blank')
            window.close()
          } else {
            this.init()
          }
          if (action == 'beforSubmit') {
            this.$refs.childrenRef.submitTaskNotBefore()
          }
          if (action == 'apply') {
            this.openUserSelector()
          }
          if (action == 'handleSubmit') {
            this.openUserSelector()
          }
        } else {
          this.$messageWorkReport.error('保存失败:' + res.message)
        }
      })
    },
    openUserSelector() {
      getAction(this.urls.flowNode + '?id=' + this.id).then((res) => {
        if (res.success) {
          this.$refs.ProcessUserSelect.doSelect(res.result, '')
        } else {
          this.$messageWorkReport.error('获取流程节点信息失败:' + res.message)
        }
      })
    },
    calcStageflowNode(stage) {
      let isNeedBudget = this.infrastructure.amount && Math.abs(this.infrastructure.amount) > 0 ? 1 : 0
      let isNeedMarjorHeader = 0 //this.infrastructure.auditAmount && Math.abs(this.infrastructure.auditAmount) > 50000 ? 1 : 0
      let nodes = []
      nodes.push(stage + '-资料员')
      nodes.push(stage + '-专业负责人')
      if (isNeedBudget == 1) {
        nodes.push(stage + '-造价专员')
        nodes.push(stage + '-造价主管')
      }
      nodes.push(stage + '-项目经理')
      if (isNeedMarjorHeader == 1) {
        nodes.push(stage + '-专业主管')
      }

      return nodes
    },
    selectUserConfirm(cols) {
      if (this.currentTask.taskDefKey == 'apply') {
        cols.forEach((c) => {
          if (c.value && c.value != null) {
            this.$set(this.custom, c.node, c.value)
          } else {
            this.$set(this.custom, c.node, '')
          }
        })
        this.$refs.childrenRef.custom = this.custom
        this.$refs.childrenRef.submitTaskNotBefore()
        return
      }
      if (cols && cols.length > 0) {
        postAction(this.urls.startFlow + '?id=' + this.id, cols).then((res) => {
          if (res.success) {
            this.$messageWorkReport.success('提交审批成功')
            this.refreshSelectedTag(this.currentRoute)
          } else {
            this.$messageWorkReport.error('提交审批失败:' + res.message)
          }
        })
      }
    },
    handleSubmit(action) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.handleSave(action)
        } else {
          this.$messageWorkReport.warning('请根据提示将表单填写完整')
        }
      })
    },
    handleDownloadTemplate(id) {
      const token = Vue.ls.get(ACCESS_TOKEN)
      let url = process.env.VUE_APP_API_BASE_URL + '/workReport/attach/download?token=' + token + '&id=' + id
      window.open(url)
    },
    handleDownload(index) {
      let selectRows = this['selectedAttachRows' + index]
      if (!selectRows || selectRows.length <= 0) {
        if (index == 1) {
          return this.$messageWorkReport.warning('请在第一阶段附件列表中勾选需要下载的附件')
        }
        if (index == 2) {
          return this.$messageWorkReport.warning('请在第二阶段附件列表中勾选需要下载的附件')
        }
        if (index == 3) {
          return this.$messageWorkReport.warning('请在第三阶段附件列表中勾选需要下载的附件')
        }
      }
      if (selectRows.length == 1) {
        let record = selectRows[0]
        if (record.id) {
          const token = Vue.ls.get(ACCESS_TOKEN)
          let url = process.env.VUE_APP_API_BASE_URL + '/workReport/attach/download?token=' + token + '&id=' + record.id
          window.open(url)
        }
      } else {
        let newIds = []
        selectRows.forEach((r) => {
          // newIds.push(r.id + '_HTE_' + r.fileName)
          newIds.push(r.id)
        })
        // const token = Vue.ls.get(ACCESS_TOKEN)
        // let url =
        //   process.env.VUE_APP_API_BASE_URL +
        //   '/workReport/attach/downloadUnionZip?token=' +
        //   token +
        //   '&ids=' +
        //   newIds.join(',')
        this.doDownLoadBatch(newIds.join(','), index)
      }
    },
    doDownLoadBatch(attachIds, stage, ftpKey = 'ftp') {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      let stageText = ''
      if (stage == 1) {
        stageText = '第一阶段附件'
      }
      if (stage == 2) {
        stageText = '第二阶段附件'
      }
      if (stage == 3) {
        stageText = '第三阶段附件'
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame')
      let tempFileName = null
      tempFileName =
        '【' +
        this.infrastructure.applyNo +
        '】【' +
        this.infrastructure.name +
        '】【' +
        this.infrastructure.applyUser +
        '】【' +
        stageText +
        '】.zip'
      var href =
        this.API_BASE_URL +
        this.urls.downLoadBatchWithFileName +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=' +
        ftpKey +
        '&token=' +
        this.$ls.get(ACCESS_TOKEN) +
        '&zipFileName=' +
        encodeURIComponent(tempFileName)
      iframe.src = href
    },
    beforUpload(index) {
      this.stageIndex = index
    },
    afterUpload(response) {
      this.fetchAttachs(this.stageIndex)
    },
    handleDelAttach(record, index) {
      let title = ''
      if (index == '1') {
        title = '第一阶段'
      } else if (index == '2') {
        title = '第二阶段'
      } else {
        title = '第三阶段'
      }
      if (record.uploader != this.curUserId) {
        return this.$messageWorkReport.warning('请勿删除非本人上传的附件')
      }
      let that = this
      Modal.confirm({
        title: '删除提醒',
        content: `是否确定删除${title}附件[${record.fileName}]？`,
        onOk: () => {
          deleteAction(that.urls.deleteAttach + '?id=' + record.id).then((res) => {
            if (res.success) {
              that.$messageWorkReport.success('删除成功')
              that.fetchAttachs(index)
            } else {
              that.$messageWorkReport.error('删除失败:' + res.message)
            }
          })
        },
      })
    },
    fetchAttachs(index) {
      getAction(this.urls.getAttachs + '?busField=Infrastructure&busKey=' + this.id + '_stage_' + index).then((res) => {
        if (res.code == '1') {
          this.$set(this.attachs, index, res.data)
        } else {
          this.$messageWorkReport.error(res.message)
        }
      })
    },
    customAttachRow(record) {
      return {
        on: {
          dblclick: (event) => {
            this.handlePreview(record)
          },
        },
      }
    },
    handlePreview(file) {
      if (
        endWith(file.fileName, 'rar') ||
        endWith(file.fileName, 'zip') ||
        endWith(file.fileName, 'dwg') ||
        endWith(file.fileName, 'tgz')
      ) {
        return true
      }
      let params = {
        id: file.id,
        ftpKey: 'ftp',
      }
      previewAttach(params)
        .then((result) => {
          const url = URL.createObjectURL(result)
          window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + url)
        })
        .catch((err) => {
          this.$messageWorkReport.warning('下载文件失败')
        })
    },
    onSelectAttachChange(selectedRowKeys, selectedRows, index) {
      this['selectedAttachKeys' + index] = selectedRowKeys
      this['selectedAttachRows' + index] = selectedRows
    },
    getNextNum(action) {
      if (action == 1) {
        this.$set(this.infrastructure, 'num', '')
      }
      if (this.infrastructure.docType == '0') {
        if (this.infrastructure.type && this.infrastructure.contractNumber) {
          let type = 'LXD-'
          if (this.infrastructure.type == '1') {
            type = 'TZD-'
          }
          getAction(
            this.urls.getNextNum +
              '?contractNumber=' +
              this.infrastructure.contractNumber +
              '&type=' +
              type +
              '&id=' +
              this.id
          ).then((res) => {
            if (res.success) {
              this.$set(this.infrastructure, 'num', res.result)
            } else {
              this.$messageWorkReport.error('获取单据编号失败:' + res.message)
            }
          })
        }
      } else {
      }
    },
    beforeSubmit(res) {
      this.alertMsg = ''
      this.alertShow = false
      // if (this.infrastructure.auditAmount && Math.abs(this.infrastructure.auditAmount) > 50000) {
      //   this.$set(this.custom, 'isNeedMarjorHeader', '1')
      // } else {
      this.$set(this.custom, 'isNeedMarjorHeader', '0')
      // }
      if (this.infrastructure.amount && Math.abs(this.infrastructure.amount) > 0) {
        this.$set(this.custom, 'isNeedBudget', '1')
      } else {
        this.$set(this.custom, 'isNeedBudget', '0')
      }
      if (['document', 'document1', 'document2'].indexOf(this.process.taskDefKey) > -1) {
        if (this.infrastructure.amount == 0) {
          Modal.confirm({
            title: '请确认申报金额',
            content: '当前申报金额为0',
            onOk: () => {
              this.handleSubmit('beforSubmit')
            },
          })
        } else if (!this.infrastructure.amount) {
          Modal.confirm({
            title: '请确认申报金额',
            content: '请正确填写申报金额',
            onOk: () => {
              this.handleSubmit('beforSubmit')
            },
          })
        } else {
          this.handleSubmit('beforSubmit')
        }
      } else if (['budget', 'budget1'].indexOf(this.process.taskDefKey) > -1) {
        let that = this
        if (this.infrastructure.auditAmount == 0) {
          Modal.confirm({
            title: '请确认审批金额',
            content: '当前审批金额为0',
            onOk: () => {
              if (!this.infrastructure.priceQuotation) {
                return that.$message.warning('请正确选择报价方式')
              } else {
                that.handleSubmit('beforSubmit')
              }
            },
          })
        } else if (!this.infrastructure.auditAmount || !this.infrastructure.priceQuotation) {
          Modal.confirm({
            title: '请确认审批金额,报价方式',
            content: '请正确填写审批金额和正确选择报价方式',
            onOk: () => {
              that.handleSubmit('beforSubmit')
            },
          })
        } else {
          this.handleSubmit('beforSubmit')
        }
      } else if (this.process.taskDefKey == 'apply') {
        this.submitType = 'apply'
        this.handleSubmit('apply')
      } else {
        this.handleSubmit('beforSubmit')
      }
      this.$refs.childrenRef.custom = this.custom
      return false
    },
    afterSubmit(res) {
      let that = this
      let msg = '基建现场管理单据[' + this.infrastructure.applyNo + ']同意操作已完成'
      this.alertMsg = '流程提交审批已完成'
      this.alertShow = true
      that.closeSelectedTag(that.currentRoute, this.infrastructure.flowId, msg)
      return true
    },

    beforeBack(res) {
      let that = this
      this.$refs.childrenRef.dialogTableVisible = !1
      if (!this.hasConfirm) {
        Modal.confirm({
          title: '退回提醒',
          content: `请谨慎操作！审批步骤前面的数字表示流程阶段，请勿跨阶段退回，避免流程重复审批，影响前阶段审批信息！`,
          onOk: () => {
            that.hasConfirm = true
            that.$refs.childrenRef.returnTask()
            that.hasConfirm = false
          },
          onCancel() {
            that.$refs.childrenRef.dialogTableVisible = !!1
          },
        })
      } else {
        return true
      }
      return false
    },
    changeHasContract() {
      this.$set(this.infrastructure, 'contractNumber', '')
      this.$set(this.infrastructure, 'contractName', '')
      this.$set(this.infrastructure, 'poNo', '')
      this.$set(this.infrastructure, 'supplierName', '')
      this.$set(this.infrastructure, 'supplierCode', '')
      this.$set(this.infrastructure, 'companyName', '')
      this.$set(this.infrastructure, 'companyCode', '')
      this.$set(this.infrastructure, 'costNumber', '')
    },
    fetchSignCompany() {
      getAction(this.urls.loadSignCompany, {}).then((res) => {
        if (res.code == 200) {
          this.signCompany = res.result
        } else {
          this.$messageWorkReport.warning('请求数据失败:' + res.msg)
        }
      })
    },
    changeSignCompanyCode(v) {
      this.$set(this.infrastructure, 'companyCode', v)
      if (this.infrastructure.companyCode) {
        this.signCompany.forEach((s) => {
          if (s.componyNo == this.infrastructure.companyCode) {
            this.infrastructure.companyName = s.componyName
            this.$set(this.infrastructure, 'companyName', s.componyName)
          }
        })
      } else {
        this.$set(this.infrastructure, 'signCompany', '')
      }
    },
    selectSupplier(supplier) {
      if (supplier) {
        this.$set(this.infrastructure, 'supplierName', supplier.sp_name)
        this.$set(this.infrastructure, 'supplierCode', supplier.sp_no)
      } else {
        this.$set(this.infrastructure, 'supplierName', '')
        this.$set(this.infrastructure, 'supplierCode', '')
      }
      this.showSupplierSelector = false
    },
    changeContractNumber() {
      if (!this.infrastructure.contractNumber) {
        return
      }
      if (this.searchTimeOut) {
        window.clearTimeout(this.searchTimeOut)
      }
      this.searchTimeOut = window.setTimeout(this.toChangeRecordList, 800)
    },
    toChangeRecordList() {
      if (this.infrastructure.contractNumber) {
        let changeRecordListSearchForm = {
          withInProjectClass: '40,41',
          withOutProjectTypeSubCategory: 'S',
          contractNumber: this.infrastructure.contractNumber,
          seeAll: true,
        }
        postAction(this.urls.changeRecordList, changeRecordListSearchForm).then((res) => {
          if (res.success) {
            this.changeRecords = res.result
          } else {
            this.$messageWorkReport.error('查询工程项目变更数据错误:' + res.message)
          }
        })
      }
    },
    toChangeRecordDetail(record) {
      let urlJump = this.$router.resolve({
        path:
          '/projectChange/changeRecord' +
          '?changeId=' +
          record.id +
          '&projectBuildId=' +
          record.projectBuildId +
          '&pageId=8',
      })
      window.open(urlJump.href, '_blank')
    },
    async print() {
      await this.fetchProcessComment(this.infrastructure.flowId)
      setTimeout(this.$refs.InfrastructureDetailPrint.print(), 3000)
    },
    async fetchProcessComment(flowId) {
      if (!flowId) {
        return
      }
      let res = await getAction(this.urls.getProcessComment + '/' + flowId, {})
      if (res.success) {
        this.comments = res.result
      } else {
        this.$messageWorkReport.error(res.message)
      }
    },
    openChangeRecordSelector() {
      if (!this.infrastructure.contractNumber) {
        return this.$messageWorkReport.warning('请先选择或输入合同编号')
      }
      this.$refs.ChangeRecordSelector.openInit('', '', '', '', {
        withInProjectClass: '40,41',
        withOutProjectTypeSubCategory: 'S',
        contractNumber: this.infrastructure.contractNumber,
        seeAll: true,
      })
    },
    closeChangeRecordSelector(changeRecord) {
      if (changeRecord) {
        this.$set(this.infrastructure, 'changeRecordId', changeRecord.id + '')
      }
    },
    toGuied() {
      let urlJump = this.$router.resolve({
        path: '/library/file/view/4/3563/0',
      })
      window.open(urlJump.href, '_blank')
    },
  },
  watch: {},
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.page-main {
  .container {
    /deep/ .ant-alert-success {
      text-align: center;
    }
    /deep/ .ant-alert-message {
      font-size: 20px;
      font-weight: bold;
      color: red;
    }
    .content {
      margin-top: 20px;

      section {
        margin-bottom: 18px;

        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }

          /deep/ .a-upload__input {
            display: none !important;
          }
        }
      }
    }
  }

  .tips-box {
    margin-top: 32px;

    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}

/deep/ .el-upload__input {
  display: none !important;
}

/deep/.ant-form .ant-form-item-label {
  width: 150px;
}
</style>
<style lang="less" scoped>
/deep/ .el-upload__input {
  display: none !important;
}

/deep/.ant-form .ant-form-item-label {
  width: 150px !important;
}

/deep/.ant-form .ant-form-item-control-wrapper {
  display: inline-block;
  width: calc(100% - 150px) !important;
}

/deep/ #process-container {
  width: unset !important;
}

#process-container {
  background: #fff;
  padding: 40px 22px;
  width: auto;
  margin: 0 auto;
  -webkit-box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.15);
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.15);
}
.multipleForm /deep/.ant-form-item-control-wrapper {
  width: 100% !important;
}
// .multipleForm /deep/.ant-form-item-control-wrapper {
//   width: 100% !important;
// }
// .multipleForm /deep/.ant-input{
//   width:auto !important;
// }
</style>
